﻿namespace ElisVK.Data.AudioSources
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.IO;
    using System.Text;
    using System.Threading;
    using Properties;
    using Utils;

    public class VKMyMusicAudioSource : AudioSource
    {
        private BackgroundWorker _backgroundWorker = new BackgroundWorker();

        public VKMyMusicAudioSource() : base("My Music")
        {
            BackgroundWorker.DoWork += BackgroundWorkerDoWork;
            BackgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;
        }

        private BackgroundWorker BackgroundWorker
        {
            get { return _backgroundWorker; }
        }

        public override ObservableCollection<Audio> GetAudios()
        {
            var buff = VKHelper.DownloadData(
                                "https://api.vkontakte.ru/method/audio.get.xml?access_token=" + App.SessionInfo.AccessToken);

            return new ObservableCollection<Audio>(VKHelper.ParseAudiosFromXML(Encoding.UTF8.GetString(buff)));
        }

        public override bool Synchronize()
        {
            if (BackgroundWorker.IsBusy)
                return false;

            BackgroundWorker.RunWorkerAsync();
            
            return true;
        }

        private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }

        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var audios = GetAudios();
            var realName = Name;

            if (audios.Count < 1)
                return;

            for (int i = 0; i < audios.Count; i++)
            {
                Name = string.Format("{0} {1}/{2}", realName, i, audios.Count);

                VKHelper.DownloadAudio(audios[i], Path.Combine(App.Settings.SynchronizationPath, realName));
            }

            Name = realName;
        }

    }
}
